/*
 * Copyright (c) 2000, 2025, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 *
 */

// 包含必要的头文件
#include "classfile/classFileStream.hpp"
#include "classfile/classLoader.hpp"
#include "classfile/classLoadInfo.hpp"
#include "classfile/javaClasses.inline.hpp"
#include "classfile/systemDictionary.hpp"
#include "classfile/vmSymbols.hpp"
#include "jfr/jfrEvents.hpp"
#include "jni.h"
#include "jvm.h"
#include "memory/allocation.inline.hpp"
#include "memory/resourceArea.hpp"
#include "oops/access.inline.hpp"
#include "oops/fieldStreams.inline.hpp"
#include "oops/instanceKlass.inline.hpp"
#include "oops/klass.inline.hpp"
#include "oops/objArrayOop.inline.hpp"
#include "oops/oop.inline.hpp"
#include "oops/typeArrayOop.inline.hpp"
#include "prims/jvmtiExport.hpp"
#include "prims/unsafe.hpp"
#include "runtime/globals.hpp"
#include "runtime/handles.inline.hpp"
#include "runtime/interfaceSupport.inline.hpp"
#include "runtime/javaThread.inline.hpp"
#include "runtime/jniHandles.inline.hpp"
#include "runtime/orderAccess.hpp"
#include "runtime/reflection.hpp"
#include "runtime/sharedRuntime.hpp"
#include "runtime/stubRoutines.hpp"
#include "runtime/threadSMR.hpp"
#include "runtime/vmOperations.hpp"
#include "runtime/vm_version.hpp"
#include "sanitizers/ub.hpp"
#include "services/threadService.hpp"
#include "utilities/align.hpp"
#include "utilities/copy.hpp"
#include "utilities/dtrace.hpp"
#include "utilities/macros.hpp"

/**
 * jdk.internal.misc.Unsafe 类的实现
 * 
 * Unsafe类提供了Java程序员直接访问内存、操作对象字段以及执行其他底层操作的能力。
 * 这些操作通常被认为是"不安全的"，因为它们可能破坏内存安全或绕过JVM的安全检查。
 */


#define MAX_OBJECT_SIZE \
  ( arrayOopDesc::base_offset_in_bytes(T_DOUBLE) \
    + ((julong)max_jint * sizeof(double)) )

/**
 * UNSAFE_ENTRY - 定义一个Unsafe方法的入口点（可能触发安全点）
 * @param result_type 返回值类型
 * @param header 方法声明
 */
#define UNSAFE_ENTRY(result_type, header) \
  JVM_ENTRY(static result_type, header)

/**
 * UNSAFE_LEAF - 定义一个Unsafe叶方法的入口点（不会触发安全点）
 * @param result_type 返回值类型
 * @param header 方法声明
 */
#define UNSAFE_LEAF(result_type, header) \
  JVM_LEAF(static result_type, header)

// 所有内存访问方法（如getInt, copyMemory）都必须使用此宏。
// 我们称这些方法为"作用域"方法，因为对这些方法的访问通常由"作用域"（MemorySessionImpl对象）控制，
// 当作用域不再存活时，不允许访问。
//
// 关闭作用域对象（参见scopedMemoryAccess.cpp）可能会在安全点安装异步异常。
// 当这种情况发生时，作用域方法不允许访问底层内存（因为该内存可能已被释放）。
// 因此，进入作用域方法时我们检查是否已安装异步异常，如果是则立即返回。
//
// 通常，我们不允许在作用域方法中间发生安全点。
// 如果在这样的安全点安装了异步异常握手，
// 内存访问可能在握手被访问线程处理之前仍然发生。
//
// 推论：由于处于本地状态的线程被认为处于安全点，
// 作用域方法不得在本地线程状态下执行。
// 因此，不能有UNSAFE_LEAF_SCOPED。
/**
 * UNSAFE_ENTRY_SCOPED - 定义一个作用域Unsafe方法的入口点
 * @param result_type 返回值类型
 * @param header 方法声明
 */
#define UNSAFE_ENTRY_SCOPED(result_type, header) \
  JVM_ENTRY(static result_type, header) \
  if (thread->has_async_exception_condition()) {return (result_type)0;}

/**
 * UNSAFE_END - Unsafe方法的结束标记
 */
#define UNSAFE_END JVM_END


/**
 * addr_from_java - 将Java地址(long)转换为C++指针
 * @param addr Java地址
 * @return C++指针
 */
static inline void* addr_from_java(jlong addr) {
  // 此断言在32位系统上有多种失败方式。
  // 无法预测将指针转换为long的本地代码是符号扩展还是零扩展地址。
  //assert(addr == (uintptr_t)addr, "must not be odd high bits");
  return (void*)(uintptr_t)addr;
}

/**
 * addr_to_java - 将C++指针转换为Java地址(long)
 * @param p C++指针
 * @return Java地址
 */
static inline jlong addr_to_java(void* p) {
  assert(p == (void*)(uintptr_t)p, "must not be odd high bits");
  return (uintptr_t)p;
}


// 注意：VM的obj_field及相关访问器使用字节缩放（"未缩放"）偏移量，就像unsafe方法一样。
//
// 但是，Unsafe.fieldOffset方法明确拒绝保证这一点。
// Java用户通过Unsafe API操作的字段偏移值是不透明的cookie，恰好是字节偏移量。
// 我们通过在VM和Unsafe API之间传递cookie时使用转换函数来表示这种状态。
// 目前转换函数恰好是空操作。

/**
 * field_offset_to_byte_offset - 将字段偏移转换为字节偏移
 * @param field_offset 字段偏移
 * @return 字节偏移
 */
static inline jlong field_offset_to_byte_offset(jlong field_offset) {
  return field_offset;
}

/**
 * field_offset_from_byte_offset - 将字节偏移转换为字段偏移
 * @param byte_offset 字节偏移
 * @return 字段偏移
 */
static inline int field_offset_from_byte_offset(int byte_offset) {
  return byte_offset;
}

/**
 * assert_field_offset_sane - 验证字段偏移是否合理
 * @param p 对象指针
 * @param field_offset 字段偏移
 */
static inline void assert_field_offset_sane(oop p, jlong field_offset) {
#ifdef ASSERT
  jlong byte_offset = field_offset_to_byte_offset(field_offset);

  if (p != nullptr) {
    assert(byte_offset >= 0 && byte_offset <= (jlong)MAX_OBJECT_SIZE, "sane offset");
    if (byte_offset == (jint)byte_offset) {
      void* ptr_plus_disp = cast_from_oop<address>(p) + byte_offset;
      assert(p->field_addr<void>((jint)byte_offset) == ptr_plus_disp,
             "raw [ptr+disp] must be consistent with oop::field_addr");
    }
    jlong p_size = HeapWordSize * (jlong)(p->size());
    assert(byte_offset < p_size, "Unsafe access: offset " INT64_FORMAT " > object's size " INT64_FORMAT, (int64_t)byte_offset, (int64_t)p_size);
  }
#endif
}

/**
 * index_oop_from_field_offset_long - 根据对象和字段偏移计算内存地址
 * @param p 对象指针
 * @param field_offset 字段偏移
 * @return 内存地址
 */
static inline void* index_oop_from_field_offset_long(oop p, jlong field_offset) {
  assert_field_offset_sane(p, field_offset);
  uintptr_t base_address = cast_from_oop<uintptr_t>(p);
  uintptr_t byte_offset  = (uintptr_t)field_offset_to_byte_offset(field_offset);
  return (void*)(base_address + byte_offset);
}

// 外部可调用版本：
// (在模拟不安全原语的编译器内在函数中使用。)
/**
 * Unsafe_field_offset_to_byte_offset - 外部可调用的字段偏移转字节偏移函数
 * @param field_offset 字段偏移
 * @return 字节偏移
 */
jlong Unsafe_field_offset_to_byte_offset(jlong field_offset) {
  return field_offset;
}

/**
 * Unsafe_field_offset_from_byte_offset - 外部可调用的字节偏移转字段偏移函数
 * @param byte_offset 字节偏移
 * @return 字段偏移
 */
jlong Unsafe_field_offset_from_byte_offset(jlong byte_offset) {
  return byte_offset;
}


///// Java堆和本地(堆外)内存上的数据读/写

/**
 * GuardUnsafeAccess - 辅助类，用于在JavaThread::doing_unsafe_access()中包装内存访问
 * 
 * 这个类确保在进行不安全内存访问时设置线程状态，
 * 以便在发生内存访问错误时能够正确处理。
 */
class GuardUnsafeAccess {
  JavaThread* _thread;

public:
  /**
   * 构造函数 - 设置线程的不安全访问状态
   * @param thread 当前线程
   */
  GuardUnsafeAccess(JavaThread* thread) : _thread(thread) {
    // 本地/堆外访问可能会引发SIGBUS，
    // 如果访问文件中已被截断且现在无效的内存映射文件数据区域。
    _thread->set_doing_unsafe_access(true);
  }

  /**
   * 析构函数 - 清除线程的不安全访问状态
   */
  ~GuardUnsafeAccess() {
    _thread->set_doing_unsafe_access(false);
  }
};

/**
 * MemoryAccess - 访问内存的辅助模板类
 * 
 * 规范化值并在需要时在JavaThread::doing_unsafe_access()中包装访问。
 * 支持普通访问和volatile访问两种模式。
 */
template <typename T>
class MemoryAccess : StackObj {
  JavaThread* _thread;
  oop _obj;
  ptrdiff_t _offset;

  /**
   * addr - 解析并返回内存访问的地址
   * 
   * 这个原始内存访问可能会出错，所以我们确保它发生在受保护的范围内，
   * 至少通过使访问volatile来实现。由于Thread::set_doing_unsafe_access()的存储也是volatile的，
   * 编译器不能重新排序这些访问。因此，如果访问触发了错误，
   * 我们将知道Thread::doing_unsafe_access()返回true。
   * 
   * @return volatile指针到目标内存地址
   */
  volatile T* addr() {
    void* addr = index_oop_from_field_offset_long(_obj, _offset);
    return static_cast<volatile T*>(addr);
  }

  /**
   * normalize_for_write - 规范化写入值
   * @param x 原始值
   * @return 规范化后的值
   */
  template <typename U>
  U normalize_for_write(U x) {
    return x;
  }

  /**
   * normalize_for_write - 规范化布尔值写入
   * @param x 原始布尔值
   * @return 规范化后的布尔值
   */
  jboolean normalize_for_write(jboolean x) {
    return x & 1;
  }

  /**
   * normalize_for_read - 规范化读取值
   * @param x 原始值
   * @return 规范化后的值
   */
  template <typename U>
  U normalize_for_read(U x) {
    return x;
  }

  /**
   * normalize_for_read - 规范化布尔值读取
   * @param x 原始布尔值
   * @return 规范化后的布尔值
   */
  jboolean normalize_for_read(jboolean x) {
    return x != 0;
  }

public:
  /**
   * 构造函数 - 初始化内存访问参数
   * @param thread 当前线程
   * @param obj Java对象句柄
   * @param offset 内存偏移量
   */
  MemoryAccess(JavaThread* thread, jobject obj, jlong offset)
    : _thread(thread), _obj(JNIHandles::resolve(obj)), _offset((ptrdiff_t)offset) {
    assert_field_offset_sane(_obj, offset);
  }

  /**
   * get - 获取值（普通访问）
   * @return 读取到的值
   */
  T get() {
    GuardUnsafeAccess guard(_thread);
    return normalize_for_read(*addr());
  }

  /**
   * put - 设置值（普通访问）
   * 
   * 我们在某些地方使用此方法写入0，例如引起崩溃；
   * ubsan不知道这是期望的行为
   * 
   * @param x 要写入的值
   */
  // we use this method at some places for writing to 0 e.g. to cause a crash;
  // ubsan does not know that this is the desired behavior
  ATTRIBUTE_NO_UBSAN
  void put(T x) {
    GuardUnsafeAccess guard(_thread);
    *addr() = normalize_for_write(x);
  }

  /**
   * get_volatile - 获取值（volatile访问）
   * @return 读取到的值
   */
  T get_volatile() {
    GuardUnsafeAccess guard(_thread);
    volatile T ret = RawAccess<MO_SEQ_CST>::load(addr());
    return normalize_for_read(ret);
  }

  /**
   * put_volatile - 设置值（volatile访问）
   * @param x 要写入的值
   */
  void put_volatile(T x) {
    GuardUnsafeAccess guard(_thread);
    RawAccess<MO_SEQ_CST>::store(addr(), normalize_for_write(x));
  }
};

// 这些函数允许空基指针和任意地址。
// 但如果基指针非空，偏移量应该有意义。
// 也就是说，它应该在[0, MAX_OBJECT_SIZE]范围内。

/**
 * Unsafe_GetReference - 获取对象中指定偏移量处的引用值
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param obj 目标对象
 * @param offset 字段偏移量
 * @return 对象引用
 */
UNSAFE_ENTRY(jobject, Unsafe_GetReference(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) {
  oop p = JNIHandles::resolve(obj);
  assert_field_offset_sane(p, offset);
  oop v = HeapAccess<ON_UNKNOWN_OOP_REF>::oop_load_at(p, offset);
  return JNIHandles::make_local(THREAD, v);
} UNSAFE_END

/**
 * Unsafe_PutReference - 设置对象中指定偏移量处的引用值
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param obj 目标对象
 * @param offset 字段偏移量
 * @param x_h 要设置的引用值
 */
UNSAFE_ENTRY(void, Unsafe_PutReference(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h)) {
  oop x = JNIHandles::resolve(x_h);
  oop p = JNIHandles::resolve(obj);
  assert_field_offset_sane(p, offset);
  HeapAccess<ON_UNKNOWN_OOP_REF>::oop_store_at(p, offset, x);
} UNSAFE_END

/**
 * Unsafe_GetReferenceVolatile - 原子地获取对象中指定偏移量处的引用值（volatile语义）
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param obj 目标对象
 * @param offset 字段偏移量
 * @return 对象引用
 */
UNSAFE_ENTRY(jobject, Unsafe_GetReferenceVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) {
  oop p = JNIHandles::resolve(obj);
  assert_field_offset_sane(p, offset);
  oop v = HeapAccess<MO_SEQ_CST | ON_UNKNOWN_OOP_REF>::oop_load_at(p, offset);
  return JNIHandles::make_local(THREAD, v);
} UNSAFE_END

/**
 * Unsafe_PutReferenceVolatile - 原子地设置对象中指定偏移量处的引用值（volatile语义）
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param obj 目标对象
 * @param offset 字段偏移量
 * @param x_h 要设置的引用值
 */
UNSAFE_ENTRY(void, Unsafe_PutReferenceVolatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject x_h)) {
  oop x = JNIHandles::resolve(x_h);
  oop p = JNIHandles::resolve(obj);
  assert_field_offset_sane(p, offset);
  HeapAccess<MO_SEQ_CST | ON_UNKNOWN_OOP_REF>::oop_store_at(p, offset, x);
} UNSAFE_END

/**
 * Unsafe_GetUncompressedObject - 从指定地址获取未压缩的对象引用
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param addr 内存地址
 * @return 对象引用
 */
UNSAFE_ENTRY(jobject, Unsafe_GetUncompressedObject(JNIEnv *env, jobject unsafe, jlong addr)) {
  oop v = *(oop*) (address) addr;
  return JNIHandles::make_local(THREAD, v);
} UNSAFE_END

/**
 * DEFINE_GETSETOOP - 定义基本数据类型的非volatile读写操作宏
 * 
 * 为每种基本数据类型生成对应的Get和Put方法
 * 包括：Boolean, Byte, Short, Char, Int, Long, Float, Double
 */
#define DEFINE_GETSETOOP(java_type, Type) \
 \
/**
 * Unsafe_Get##Type - 获取对象中指定偏移量处的基本数据类型值
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param obj 目标对象
 * @param offset 字段偏移量
 * @return 指定类型的数据值
 */ \
UNSAFE_ENTRY_SCOPED(java_type, Unsafe_Get##Type(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) { \
  return MemoryAccess<java_type>(thread, obj, offset).get(); \
} UNSAFE_END \
 \
/**
 * Unsafe_Put##Type - 设置对象中指定偏移量处的基本数据类型值
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param obj 目标对象
 * @param offset 字段偏移量
 * @param x 要设置的值
 */ \
UNSAFE_ENTRY_SCOPED(void, Unsafe_Put##Type(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, java_type x)) { \
  MemoryAccess<java_type>(thread, obj, offset).put(x); \
} UNSAFE_END \
 \
// END DEFINE_GETSETOOP.

DEFINE_GETSETOOP(jboolean, Boolean)
DEFINE_GETSETOOP(jbyte, Byte)
DEFINE_GETSETOOP(jshort, Short);
DEFINE_GETSETOOP(jchar, Char);
DEFINE_GETSETOOP(jint, Int);
DEFINE_GETSETOOP(jlong, Long);
DEFINE_GETSETOOP(jfloat, Float);
DEFINE_GETSETOOP(jdouble, Double);

#undef DEFINE_GETSETOOP

/**
 * DEFINE_GETSETOOP_VOLATILE - 定义基本数据类型的volatile读写操作宏
 * 
 * 为每种基本数据类型生成对应的volatile Get和Put方法
 * 包括：Boolean, Byte, Short, Char, Int, Long, Float, Double
 */
#define DEFINE_GETSETOOP_VOLATILE(java_type, Type) \
 \
/**
 * Unsafe_Get##Type##Volatile - 原子地获取对象中指定偏移量处的基本数据类型值（volatile语义）
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param obj 目标对象
 * @param offset 字段偏移量
 * @return 指定类型的数据值
 */ \
UNSAFE_ENTRY_SCOPED(java_type, Unsafe_Get##Type##Volatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset)) { \
  return MemoryAccess<java_type>(thread, obj, offset).get_volatile(); \
} UNSAFE_END \
 \
/**
 * Unsafe_Put##Type##Volatile - 原子地设置对象中指定偏移量处的基本数据类型值（volatile语义）
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param obj 目标对象
 * @param offset 字段偏移量
 * @param x 要设置的值
 */ \
UNSAFE_ENTRY_SCOPED(void, Unsafe_Put##Type##Volatile(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, java_type x)) { \
  MemoryAccess<java_type>(thread, obj, offset).put_volatile(x); \
} UNSAFE_END \
 \
// END DEFINE_GETSETOOP_VOLATILE.

DEFINE_GETSETOOP_VOLATILE(jboolean, Boolean)
DEFINE_GETSETOOP_VOLATILE(jbyte, Byte)
DEFINE_GETSETOOP_VOLATILE(jshort, Short);
DEFINE_GETSETOOP_VOLATILE(jchar, Char);
DEFINE_GETSETOOP_VOLATILE(jint, Int);
DEFINE_GETSETOOP_VOLATILE(jlong, Long);
DEFINE_GETSETOOP_VOLATILE(jfloat, Float);
DEFINE_GETSETOOP_VOLATILE(jdouble, Double);

#undef DEFINE_GETSETOOP_VOLATILE

/**
 * Unsafe_FullFence - 执行内存屏障操作，确保内存操作的完全排序
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 */
UNSAFE_LEAF(void, Unsafe_FullFence(JNIEnv *env, jobject unsafe)) {
  OrderAccess::fence();
} UNSAFE_END

////// Allocation requests

/**
 * Unsafe_AllocateInstance - 分配类的实例但不调用构造函数
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param cls 要实例化的类
 * @return 新创建的实例对象
 */
UNSAFE_ENTRY(jobject, Unsafe_AllocateInstance(JNIEnv *env, jobject unsafe, jclass cls)) {
  JvmtiVMObjectAllocEventCollector oam;
  instanceOop i = InstanceKlass::allocate_instance(JNIHandles::resolve_non_null(cls), CHECK_NULL);
  return JNIHandles::make_local(THREAD, i);
} UNSAFE_END

/**
 * Unsafe_AllocateMemory0 - 分配指定大小的本地内存
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param size 要分配的内存大小
 * @return 分配的内存地址
 */
UNSAFE_LEAF(jlong, Unsafe_AllocateMemory0(JNIEnv *env, jobject unsafe, jlong size)) {
  size_t sz = (size_t)size;

  assert(is_aligned(sz, HeapWordSize), "sz not aligned");

  void* x = os::malloc(sz, mtOther);

  return addr_to_java(x);
} UNSAFE_END

/**
 * Unsafe_ReallocateMemory0 - 重新分配本地内存
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param addr 原始内存地址
 * @param size 新的内存大小
 * @return 重新分配的内存地址
 */
UNSAFE_LEAF(jlong, Unsafe_ReallocateMemory0(JNIEnv *env, jobject unsafe, jlong addr, jlong size)) {
  void* p = addr_from_java(addr);
  size_t sz = (size_t)size;

  assert(is_aligned(sz, HeapWordSize), "sz not aligned");

  void* x = os::realloc(p, sz, mtOther);

  return addr_to_java(x);
} UNSAFE_END

/**
 * Unsafe_FreeMemory0 - 释放本地内存
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param addr 要释放的内存地址
 */
UNSAFE_LEAF(void, Unsafe_FreeMemory0(JNIEnv *env, jobject unsafe, jlong addr)) {
  void* p = addr_from_java(addr);

  os::free(p);
} UNSAFE_END

/**
 * Unsafe_SetMemory0 - 设置内存区域的值
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param obj 目标对象（如果为null，则使用绝对地址）
 * @param offset 内存偏移量
 * @param size 内存区域大小
 * @param value 要设置的值
 */
UNSAFE_ENTRY_SCOPED(void, Unsafe_SetMemory0(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong size, jbyte value)) {
  size_t sz = (size_t)size;

  oop base = JNIHandles::resolve(obj);
  void* p = index_oop_from_field_offset_long(base, offset);

  {
    GuardUnsafeAccess guard(thread);
    if (StubRoutines::unsafe_setmemory() != nullptr) {
      MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXExec, thread));
      StubRoutines::UnsafeSetMemory_stub()(p, sz, value);
    } else {
      Copy::fill_to_memory_atomic(p, sz, value);
    }
  }
} UNSAFE_END

/**
 * Unsafe_CopyMemory0 - 复制内存区域
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param srcObj 源对象（如果为null，则使用绝对地址）
 * @param srcOffset 源内存偏移量
 * @param dstObj 目标对象（如果为null，则使用绝对地址）
 * @param dstOffset 目标内存偏移量
 * @param size 要复制的内存大小
 */
UNSAFE_ENTRY_SCOPED(void, Unsafe_CopyMemory0(JNIEnv *env, jobject unsafe, jobject srcObj, jlong srcOffset, jobject dstObj, jlong dstOffset, jlong size)) {
  size_t sz = (size_t)size;

  oop srcp = JNIHandles::resolve(srcObj);
  oop dstp = JNIHandles::resolve(dstObj);

  void* src = index_oop_from_field_offset_long(srcp, srcOffset);
  void* dst = index_oop_from_field_offset_long(dstp, dstOffset);
  {
    GuardUnsafeAccess guard(thread);
    if (StubRoutines::unsafe_arraycopy() != nullptr) {
      MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXExec, thread));
      StubRoutines::UnsafeArrayCopy_stub()(src, dst, sz);
    } else {
      Copy::conjoint_memory_atomic(src, dst, sz);
    }
  }
} UNSAFE_END

/**
 * Unsafe_CopySwapMemory0 - 复制并交换内存区域（按元素大小）
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param srcObj 源对象（如果为null，则使用绝对地址）
 * @param srcOffset 源内存偏移量
 * @param dstObj 目标对象（如果为null，则使用绝对地址）
 * @param dstOffset 目标内存偏移量
 * @param size 要复制的内存总大小
 * @param elemSize 元素大小（用于交换）
 */
UNSAFE_ENTRY_SCOPED(void, Unsafe_CopySwapMemory0(JNIEnv *env, jobject unsafe, jobject srcObj, jlong srcOffset, jobject dstObj, jlong dstOffset, jlong size, jlong elemSize)) {
  size_t sz = (size_t)size;
  size_t esz = (size_t)elemSize;

  oop srcp = JNIHandles::resolve(srcObj);
  oop dstp = JNIHandles::resolve(dstObj);

  address src = (address)index_oop_from_field_offset_long(srcp, srcOffset);
  address dst = (address)index_oop_from_field_offset_long(dstp, dstOffset);

  {
    GuardUnsafeAccess guard(thread);
    Copy::conjoint_swap(src, dst, sz, esz);
  }
} UNSAFE_END

/**
 * Unsafe_WriteBack0 - 写回数据缓存行
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param line 缓存行地址
 */
UNSAFE_LEAF (void, Unsafe_WriteBack0(JNIEnv *env, jobject unsafe, jlong line)) {
  assert(VM_Version::supports_data_cache_line_flush(), "should not get here");
#ifdef ASSERT
  if (TraceMemoryWriteback) {
    tty->print_cr("Unsafe: writeback 0x%p", addr_from_java(line));
  }
#endif

  MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXExec, Thread::current()));
  assert(StubRoutines::data_cache_writeback() != nullptr, "sanity");
  (StubRoutines::DataCacheWriteback_stub())(addr_from_java(line));
} UNSAFE_END

/**
 * doWriteBackSync0 - 执行写回同步操作
 * @param is_pre 是否为预同步
 */
static void doWriteBackSync0(bool is_pre)
{
  MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXExec, Thread::current()));
  assert(StubRoutines::data_cache_writeback_sync() != nullptr, "sanity");
  (StubRoutines::DataCacheWritebackSync_stub())(is_pre);
}

/**
 * Unsafe_WriteBackPreSync0 - 写回预同步操作
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 */
UNSAFE_LEAF (void, Unsafe_WriteBackPreSync0(JNIEnv *env, jobject unsafe)) {
  assert(VM_Version::supports_data_cache_line_flush(), "should not get here");
#ifdef ASSERT
  if (TraceMemoryWriteback) {
      tty->print_cr("Unsafe: writeback pre-sync");
  }
#endif

  doWriteBackSync0(true);
} UNSAFE_END

/**
 * Unsafe_WriteBackPostSync0 - 写回后同步操作
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 */
UNSAFE_LEAF (void, Unsafe_WriteBackPostSync0(JNIEnv *env, jobject unsafe)) {
  assert(VM_Version::supports_data_cache_line_flush(), "should not get here");
#ifdef ASSERT
  if (TraceMemoryWriteback) {
    tty->print_cr("Unsafe: writeback pre-sync");
  }
#endif

  doWriteBackSync0(false);
} UNSAFE_END

////// Random queries

// 查找具有匹配名称的字段的对象字段偏移量，或错误代码
// 错误代码 -1 表示未找到，-2 表示静态字段
/**
 * find_known_instance_field_offset - 根据类和字段名查找实例字段偏移量
 * 
 * @param clazz 类对象
 * @param name 字段名
 * @param THREAD 当前线程
 * @return 字段偏移量或错误代码(-1表示未找到，-2表示静态字段)
 */
static jlong find_known_instance_field_offset(jclass clazz, jstring name, TRAPS) {
  assert(clazz != nullptr, "clazz must not be null");
  assert(name != nullptr, "name must not be null");

  ResourceMark rm(THREAD);
  char *utf_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));

  InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz)));

  jint offset = -1; // Not found
  for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
    Symbol *name = fs.name();
    if (name->equals(utf_name)) {
      if (!fs.access_flags().is_static()) {
        offset = fs.offset();
      } else {
        offset = -2; // A static field
      }
      break;
    }
  }
  if (offset < 0) {
    return offset; // Error code
  }
  return field_offset_from_byte_offset(offset);
}

/**
 * find_field_offset - 查找字段偏移量
 * 
 * @param field Java反射Field对象
 * @param must_be_static 是否必须为静态字段（-1表示不检查，0表示必须为实例字段，1表示必须为静态字段）
 * @param THREAD 当前线程
 * @return 字段偏移量
 */
static jlong find_field_offset(jobject field, int must_be_static, TRAPS) {
  assert(field != nullptr, "field must not be null");

  oop reflected   = JNIHandles::resolve_non_null(field);
  oop mirror      = java_lang_reflect_Field::clazz(reflected);
  Klass* k        = java_lang_Class::as_Klass(mirror);
  int slot        = java_lang_reflect_Field::slot(reflected);
  int modifiers   = java_lang_reflect_Field::modifiers(reflected);

  if (must_be_static >= 0) {
    int really_is_static = ((modifiers & JVM_ACC_STATIC) != 0);
    if (must_be_static != really_is_static) {
      THROW_0(vmSymbols::java_lang_IllegalArgumentException());
    }
  }

  int offset = InstanceKlass::cast(k)->field_offset(slot);
  return field_offset_from_byte_offset(offset);
}

/**
 * Unsafe_ObjectFieldOffset0 - 获取对象字段的偏移量
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param field Java反射Field对象
 * @return 字段偏移量
 */
UNSAFE_ENTRY(jlong, Unsafe_ObjectFieldOffset0(JNIEnv *env, jobject unsafe, jobject field)) {
  return find_field_offset(field, 0, THREAD);
} UNSAFE_END

/**
 * Unsafe_KnownObjectFieldOffset0 - 获取已知对象字段的偏移量
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param c 类对象
 * @param name 字段名
 * @return 字段偏移量或错误代码
 */
UNSAFE_ENTRY(jlong, Unsafe_KnownObjectFieldOffset0(JNIEnv *env, jobject unsafe, jclass c, jstring name)) {
  return find_known_instance_field_offset(c, name, THREAD);
} UNSAFE_END

/**
 * Unsafe_StaticFieldOffset0 - 获取静态字段的偏移量
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param field Java反射Field对象
 * @return 字段偏移量
 */
UNSAFE_ENTRY(jlong, Unsafe_StaticFieldOffset0(JNIEnv *env, jobject unsafe, jobject field)) {
  return find_field_offset(field, 1, THREAD);
} UNSAFE_END

/**
 * Unsafe_StaticFieldBase0 - 获取静态字段的基地址
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param field Java反射Field对象
 * @return 静态字段的基对象
 */
UNSAFE_ENTRY(jobject, Unsafe_StaticFieldBase0(JNIEnv *env, jobject unsafe, jobject field)) {
  assert(field != nullptr, "field must not be null");

  // 注意：在此VM实现中，字段地址始终是klass元对象基址的短偏移量。
  // 因此，返回类型的完整动态范围永远不会被使用。
  // 但是，某些实现可能会将静态字段放在许多类共享的数组中，
  // 甚至放在固定地址上，在这种情况下，地址可能相当大。
  // 在最后一种情况下，此函数将返回null，因为地址将独立操作，没有任何基指针。

  oop reflected   = JNIHandles::resolve_non_null(field);
  oop mirror      = java_lang_reflect_Field::clazz(reflected);
  int modifiers   = java_lang_reflect_Field::modifiers(reflected);

  if ((modifiers & JVM_ACC_STATIC) == 0) {
    THROW_NULL(vmSymbols::java_lang_IllegalArgumentException());
  }

  return JNIHandles::make_local(THREAD, mirror);
} UNSAFE_END

/**
 * Unsafe_EnsureClassInitialized0 - 确保类已被初始化
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param clazz 类对象
 */
UNSAFE_ENTRY(void, Unsafe_EnsureClassInitialized0(JNIEnv *env, jobject unsafe, jobject clazz)) {
  assert(clazz != nullptr, "clazz must not be null");

  oop mirror = JNIHandles::resolve_non_null(clazz);

  Klass* klass = java_lang_Class::as_Klass(mirror);
  if (klass != nullptr && klass->should_be_initialized()) {
    InstanceKlass* k = InstanceKlass::cast(klass);
    k->initialize(CHECK);
  }
}
UNSAFE_END

/**
 * Unsafe_ShouldBeInitialized0 - 检查类是否应该被初始化
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param clazz 类对象
 * @return 如果类应该被初始化则返回true，否则返回false
 */
UNSAFE_ENTRY(jboolean, Unsafe_ShouldBeInitialized0(JNIEnv *env, jobject unsafe, jobject clazz)) {
  assert(clazz != nullptr, "clazz must not be null");

  oop mirror = JNIHandles::resolve_non_null(clazz);
  Klass* klass = java_lang_Class::as_Klass(mirror);

  if (klass != nullptr && klass->should_be_initialized()) {
    return true;
  }

  return false;
}
UNSAFE_END

/**
 * getBaseAndScale - 获取数组的基地址和缩放因子
 * 
 * @param base 输出参数，数组基地址
 * @param scale 输出参数，数组元素缩放因子
 * @param clazz 数组类
 * @param THREAD 当前线程
 */
static void getBaseAndScale(int& base, int& scale, jclass clazz, TRAPS) {
  assert(clazz != nullptr, "clazz must not be null");

  oop mirror = JNIHandles::resolve_non_null(clazz);
  Klass* k = java_lang_Class::as_Klass(mirror);

  if (k == nullptr || !k->is_array_klass()) {
    THROW(vmSymbols::java_lang_InvalidClassException());
  } else if (k->is_objArray_klass()) {
    base  = arrayOopDesc::base_offset_in_bytes(T_OBJECT);
    scale = heapOopSize;
  } else if (k->is_typeArray_klass()) {
    TypeArrayKlass* tak = TypeArrayKlass::cast(k);
    base  = tak->array_header_in_bytes();
    assert(base == arrayOopDesc::base_offset_in_bytes(tak->element_type()), "array_header_size semantics ok");
    scale = (1 << tak->log2_element_size());
  } else {
    ShouldNotReachHere();
  }
}

/**
 * Unsafe_ArrayBaseOffset0 - 获取数组基地址偏移量
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param clazz 数组类
 * @return 数组基地址偏移量
 */
UNSAFE_ENTRY(jint, Unsafe_ArrayBaseOffset0(JNIEnv *env, jobject unsafe, jclass clazz)) {
  int base = 0, scale = 0;
  getBaseAndScale(base, scale, clazz, CHECK_0);

  return field_offset_from_byte_offset(base);
} UNSAFE_END

/**
 * Unsafe_ArrayIndexScale0 - 获取数组索引缩放因子
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param clazz 数组类
 * @return 数组索引缩放因子
 */
UNSAFE_ENTRY(jint, Unsafe_ArrayIndexScale0(JNIEnv *env, jobject unsafe, jclass clazz)) {
  int base = 0, scale = 0;
  getBaseAndScale(base, scale, clazz, CHECK_0);

  // 此VM将字段和数组元素都打包到字节级别。
  // 但要注意：如果发生更改，使得给定基本类型（例如，T_BOOLEAN）的数组引用
  // 使用与字段不同的内存单位，则此方法必须为这样的数组返回零。
  // 例如，VM过去在对象布局中将子字大小的字段存储在完整的单词中，
  // 因此像getByte(Object,int)这样的访问器实际上并不像人们期望的那样工作。
  // 因此，此函数过去会报告零缩放因子，以便用户知道不要尝试访问子字数组元素。
  // // 未打包字段的代码：
  // if (scale < wordSize)  return 0;

  // 以下允许相当通用的fieldOffset cookie方案，
  // 但要求它在线性字节偏移中。
  return field_offset_from_byte_offset(scale) - field_offset_from_byte_offset(0);
} UNSAFE_END

/**
 * throw_new - 抛出新的Java异常
 * 
 * @param env JNI环境指针
 * @param ename 异常类名
 */
static inline void throw_new(JNIEnv *env, const char *ename) {
  jclass cls = env->FindClass(ename);
  if (env->ExceptionCheck()) {
    env->ExceptionClear();
    tty->print_cr("Unsafe: cannot throw %s because FindClass has failed", ename);
    return;
  }

  env->ThrowNew(cls, nullptr);
}

/**
 * Unsafe_DefineClass_impl - 实现类定义功能
 * 
 * @param env JNI环境指针
 * @param name 类名
 * @param data 类字节数组
 * @param offset 数据偏移量
 * @param length 数据长度
 * @param loader 类加载器
 * @param pd ProtectionDomain
 * @return 定义的类
 */
static jclass Unsafe_DefineClass_impl(JNIEnv *env, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd) {
  // 代码来自JDK 1.3 ClassLoader.c

  jbyte *body;
  char *utfName = nullptr;
  jclass result = nullptr;
  char buf[128];

  assert(data != nullptr, "Class bytes must not be null");
  assert(length >= 0, "length must not be negative: %d", length);

  if (UsePerfData) {
    ClassLoader::unsafe_defineClassCallCounter()->inc();
  }

  body = NEW_C_HEAP_ARRAY_RETURN_NULL(jbyte, length, mtInternal);
  if (body == nullptr) {
    throw_new(env, "java/lang/OutOfMemoryError");
    return nullptr;
  }

  env->GetByteArrayRegion(data, offset, length, body);
  if (env->ExceptionCheck()) {
    goto free_body;
  }

  if (name != nullptr) {
    uint len = env->GetStringUTFLength(name);
    int unicode_len = env->GetStringLength(name);

    if (len >= sizeof(buf)) {
      utfName = NEW_C_HEAP_ARRAY_RETURN_NULL(char, len + 1, mtInternal);
      if (utfName == nullptr) {
        throw_new(env, "java/lang/OutOfMemoryError");
        goto free_body;
      }
    } else {
      utfName = buf;
    }

    env->GetStringUTFRegion(name, 0, unicode_len, utfName);

    for (uint i = 0; i < len; i++) {
      if (utfName[i] == '.')   utfName[i] = '/';
    }
  }

  result = JVM_DefineClass(env, utfName, loader, body, length, pd);

  if (utfName && utfName != buf) {
    FREE_C_HEAP_ARRAY(char, utfName);
  }

 free_body:
  FREE_C_HEAP_ARRAY(jbyte, body);
  return result;
}

/**
 * Unsafe_DefineClass0 - 定义类
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param name 类名
 * @param data 类字节数组
 * @param offset 数据偏移量
 * @param length 数据长度
 * @param loader 类加载器
 * @param pd ProtectionDomain
 * @return 定义的类
 */
UNSAFE_ENTRY(jclass, Unsafe_DefineClass0(JNIEnv *env, jobject unsafe, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd)) {
  ThreadToNativeFromVM ttnfv(thread);

  return Unsafe_DefineClass_impl(env, name, data, offset, length, loader, pd);
} UNSAFE_END

/**
 * Unsafe_ThrowException - 抛出异常
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param thr 要抛出的异常
 */
UNSAFE_ENTRY(void, Unsafe_ThrowException(JNIEnv *env, jobject unsafe, jthrowable thr)) {
  ThreadToNativeFromVM ttnfv(thread);
  env->Throw(thr);
} UNSAFE_END

// JSR166 ------------------------------------------------------------------

/**
 * Unsafe_CompareAndExchangeReference - 比较并交换对象引用（原子操作）
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param obj 目标对象
 * @param offset 字段偏移量
 * @param e_h 期望值
 * @param x_h 新值
 * @return 交换前的值
 */
UNSAFE_ENTRY(jobject, Unsafe_CompareAndExchangeReference(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject e_h, jobject x_h)) {
  oop x = JNIHandles::resolve(x_h);
  oop e = JNIHandles::resolve(e_h);
  oop p = JNIHandles::resolve(obj);
  assert_field_offset_sane(p, offset);
  oop res = HeapAccess<ON_UNKNOWN_OOP_REF>::oop_atomic_cmpxchg_at(p, (ptrdiff_t)offset, e, x);
  return JNIHandles::make_local(THREAD, res);
} UNSAFE_END

/**
 * Unsafe_CompareAndExchangeInt - 比较并交换int值（原子操作）
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param obj 目标对象
 * @param offset 字段偏移量
 * @param e 期望值
 * @param x 新值
 * @return 交换前的值
 */
UNSAFE_ENTRY_SCOPED(jint, Unsafe_CompareAndExchangeInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint e, jint x)) {
  oop p = JNIHandles::resolve(obj);
  volatile jint* addr = (volatile jint*)index_oop_from_field_offset_long(p, offset);
  return Atomic::cmpxchg(addr, e, x);
} UNSAFE_END

/**
 * Unsafe_CompareAndExchangeLong - 比较并交换long值（原子操作）
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param obj 目标对象
 * @param offset 字段偏移量
 * @param e 期望值
 * @param x 新值
 * @return 交换前的值
 */
UNSAFE_ENTRY_SCOPED(jlong, Unsafe_CompareAndExchangeLong(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong e, jlong x)) {
  oop p = JNIHandles::resolve(obj);
  volatile jlong* addr = (volatile jlong*)index_oop_from_field_offset_long(p, offset);
  return Atomic::cmpxchg(addr, e, x);
} UNSAFE_END

/**
 * Unsafe_CompareAndSetReference - 比较并设置对象引用（原子操作）
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param obj 目标对象
 * @param offset 字段偏移量
 * @param e_h 期望值
 * @param x_h 新值
 * @return 如果交换成功返回true，否则返回false
 */
UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSetReference(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jobject e_h, jobject x_h)) {
  oop x = JNIHandles::resolve(x_h);
  oop e = JNIHandles::resolve(e_h);
  oop p = JNIHandles::resolve(obj);
  assert_field_offset_sane(p, offset);
  oop ret = HeapAccess<ON_UNKNOWN_OOP_REF>::oop_atomic_cmpxchg_at(p, (ptrdiff_t)offset, e, x);
  return ret == e;
} UNSAFE_END

/**
 * Unsafe_CompareAndSetInt - 比较并设置int值（原子操作）
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param obj 目标对象
 * @param offset 字段偏移量
 * @param e 期望值
 * @param x 新值
 * @return 如果交换成功返回true，否则返回false
 */
UNSAFE_ENTRY_SCOPED(jboolean, Unsafe_CompareAndSetInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint e, jint x)) {
  oop p = JNIHandles::resolve(obj);
  volatile jint* addr = (volatile jint*)index_oop_from_field_offset_long(p, offset);
  return Atomic::cmpxchg(addr, e, x) == e;
} UNSAFE_END

/**
 * Unsafe_CompareAndSetLong - 比较并设置long值（原子操作）
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param obj 目标对象
 * @param offset 字段偏移量
 * @param e 期望值
 * @param x 新值
 * @return 如果交换成功返回true，否则返回false
 */
UNSAFE_ENTRY_SCOPED(jboolean, Unsafe_CompareAndSetLong(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jlong e, jlong x)) {
  oop p = JNIHandles::resolve(obj);
  volatile jlong* addr = (volatile jlong*)index_oop_from_field_offset_long(p, offset);
  return Atomic::cmpxchg(addr, e, x) == e;
} UNSAFE_END

/**
 * post_thread_park_event - 发布线程park事件
 * 
 * @param event 事件对象
 * @param obj 被park的对象
 * @param timeout_nanos 超时时间（纳秒）
 * @param until_epoch_millis 截止时间（毫秒）
 */
static void post_thread_park_event(EventThreadPark* event, const oop obj, jlong timeout_nanos, jlong until_epoch_millis) {
  assert(event != nullptr, "invariant");
  event->set_parkedClass((obj != nullptr) ? obj->klass() : nullptr);
  event->set_timeout(timeout_nanos);
  event->set_until(until_epoch_millis);
  event->set_address((obj != nullptr) ? (u8)cast_from_oop<uintptr_t>(obj) : 0);
  event->commit();
}

/**
 * Unsafe_Park - 阻塞当前线程
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param isAbsolute 是否为绝对时间
 * @param time 阻塞时间（纳秒）
 */
UNSAFE_ENTRY(void, Unsafe_Park(JNIEnv *env, jobject unsafe, jboolean isAbsolute, jlong time)) {
  HOTSPOT_THREAD_PARK_BEGIN((uintptr_t) thread->parker(), (int) isAbsolute, time);
  EventThreadPark event;

  JavaThreadParkedState jtps(thread, time != 0);
  thread->parker()->park(isAbsolute != 0, time);
  if (event.should_commit()) {
    const oop obj = thread->current_park_blocker();
    if (time == 0) {
      post_thread_park_event(&event, obj, min_jlong, min_jlong);
    } else {
      if (isAbsolute != 0) {
        post_thread_park_event(&event, obj, min_jlong, time);
      } else {
        post_thread_park_event(&event, obj, time, min_jlong);
      }
    }
  }
  HOTSPOT_THREAD_PARK_END((uintptr_t) thread->parker());
} UNSAFE_END

/**
 * Unsafe_Unpark - 唤醒指定线程
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param jthread 要唤醒的线程
 */
UNSAFE_ENTRY(void, Unsafe_Unpark(JNIEnv *env, jobject unsafe, jobject jthread)) {
  if (jthread != nullptr) {
    oop thread_oop = JNIHandles::resolve_non_null(jthread);
    // 在构造嵌入的ThreadsListHandle之前获取存储在java.lang.Thread对象中的JavaThread*，
    // 这样我们就能知道JavaThread*的早期生命周期是否受保护。
    // 我们在这里使用acquire来确保如果我们看到非nullptr值，
    // 那么我们也看到了JavaThread*被添加时的主要ThreadsList更新。
    FastThreadsListHandle ftlh(thread_oop, java_lang_Thread::thread_acquire(thread_oop));
    JavaThread* thr = ftlh.protected_java_thread();
    if (thr != nullptr) {
      // 仍存活的JavaThread*受到FastThreadsListHandle的保护，因此可以安全访问。
      Parker* p = thr->parker();
      HOTSPOT_THREAD_UNPARK((uintptr_t) p);
      p->unpark();
    }
  } // FastThreadsListHandle在这里被销毁。
} UNSAFE_END

/**
 * Unsafe_GetLoadAverage0 - 获取系统负载平均值
 * 
 * @param env JNI环境指针
 * @param unsafe Unsafe实例
 * @param loadavg 存储负载平均值的数组
 * @param nelem 需要获取的元素数量
 * @return 实际获取的样本数量
 */
UNSAFE_ENTRY(jint, Unsafe_GetLoadAverage0(JNIEnv *env, jobject unsafe, jdoubleArray loadavg, jint nelem)) {
  const int max_nelem = 3;
  double la[max_nelem];
  jint ret;

  typeArrayOop a = typeArrayOop(JNIHandles::resolve_non_null(loadavg));
  assert(a->is_typeArray(), "must be type array");

  ret = os::loadavg(la, nelem);
  if (ret == -1) {
    return -1;
  }

  // 如果成功，ret是实际检索到的样本数量。
  assert(ret >= 0 && ret <= max_nelem, "Unexpected loadavg return value");
  switch(ret) {
    case 3: a->double_at_put(2, (jdouble)la[2]); // fall through
    case 2: a->double_at_put(1, (jdouble)la[1]); // fall through
    case 1: a->double_at_put(0, (jdouble)la[0]); break;
  }

  return ret;
} UNSAFE_END


/// JVM_RegisterUnsafeMethods

#define ADR "J"

#define LANG "Ljava/lang/"

#define OBJ LANG "Object;"
#define CLS LANG "Class;"
#define FLD LANG "reflect/Field;"
#define THR LANG "Throwable;"

#define DC_Args  LANG "String;[BII" LANG "ClassLoader;" "Ljava/security/ProtectionDomain;"
#define DAC_Args CLS "[B[" OBJ

#define CC (char*)  /*cast a literal from (const char*)*/
#define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)

#define DECLARE_GETPUTOOP(Type, Desc) \
    {CC "get" #Type,      CC "(" OBJ "J)" #Desc,       FN_PTR(Unsafe_Get##Type)}, \
    {CC "put" #Type,      CC "(" OBJ "J" #Desc ")V",   FN_PTR(Unsafe_Put##Type)}, \
    {CC "get" #Type "Volatile",      CC "(" OBJ "J)" #Desc,       FN_PTR(Unsafe_Get##Type##Volatile)}, \
    {CC "put" #Type "Volatile",      CC "(" OBJ "J" #Desc ")V",   FN_PTR(Unsafe_Put##Type##Volatile)}


/**
 * jdk_internal_misc_Unsafe_methods - Unsafe类的本地方法注册表
 * 
 * 定义了jdk.internal.misc.Unsafe类的所有本地方法映射
 */
static JNINativeMethod jdk_internal_misc_Unsafe_methods[] = {
    {CC "getReference",         CC "(" OBJ "J)" OBJ "",   FN_PTR(Unsafe_GetReference)},
    {CC "putReference",         CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_PutReference)},
    {CC "getReferenceVolatile", CC "(" OBJ "J)" OBJ,      FN_PTR(Unsafe_GetReferenceVolatile)},
    {CC "putReferenceVolatile", CC "(" OBJ "J" OBJ ")V",  FN_PTR(Unsafe_PutReferenceVolatile)},

    {CC "getUncompressedObject", CC "(" ADR ")" OBJ,  FN_PTR(Unsafe_GetUncompressedObject)},

    DECLARE_GETPUTOOP(Boolean, Z),
    DECLARE_GETPUTOOP(Byte, B),
    DECLARE_GETPUTOOP(Short, S),
    DECLARE_GETPUTOOP(Char, C),
    DECLARE_GETPUTOOP(Int, I),
    DECLARE_GETPUTOOP(Long, J),
    DECLARE_GETPUTOOP(Float, F),
    DECLARE_GETPUTOOP(Double, D),

    {CC "allocateMemory0",    CC "(J)" ADR,              FN_PTR(Unsafe_AllocateMemory0)},
    {CC "reallocateMemory0",  CC "(" ADR "J)" ADR,       FN_PTR(Unsafe_ReallocateMemory0)},
    {CC "freeMemory0",        CC "(" ADR ")V",           FN_PTR(Unsafe_FreeMemory0)},

    {CC "objectFieldOffset0", CC "(" FLD ")J",           FN_PTR(Unsafe_ObjectFieldOffset0)},
    {CC "knownObjectFieldOffset0", CC "(" CLS LANG "String;)J", FN_PTR(Unsafe_KnownObjectFieldOffset0)},
    {CC "staticFieldOffset0", CC "(" FLD ")J",           FN_PTR(Unsafe_StaticFieldOffset0)},
    {CC "staticFieldBase0",   CC "(" FLD ")" OBJ,        FN_PTR(Unsafe_StaticFieldBase0)},
    {CC "ensureClassInitialized0", CC "(" CLS ")V",      FN_PTR(Unsafe_EnsureClassInitialized0)},
    {CC "arrayBaseOffset0",   CC "(" CLS ")I",           FN_PTR(Unsafe_ArrayBaseOffset0)},
    {CC "arrayIndexScale0",   CC "(" CLS ")I",           FN_PTR(Unsafe_ArrayIndexScale0)},

    {CC "defineClass0",       CC "(" DC_Args ")" CLS,    FN_PTR(Unsafe_DefineClass0)},
    {CC "allocateInstance",   CC "(" CLS ")" OBJ,        FN_PTR(Unsafe_AllocateInstance)},
    {CC "throwException",     CC "(" THR ")V",           FN_PTR(Unsafe_ThrowException)},
    {CC "compareAndSetReference",CC "(" OBJ "J" OBJ "" OBJ ")Z", FN_PTR(Unsafe_CompareAndSetReference)},
    {CC "compareAndSetInt",   CC "(" OBJ "J""I""I"")Z",  FN_PTR(Unsafe_CompareAndSetInt)},
    {CC "compareAndSetLong",  CC "(" OBJ "J""J""J"")Z",  FN_PTR(Unsafe_CompareAndSetLong)},
    {CC "compareAndExchangeReference", CC "(" OBJ "J" OBJ "" OBJ ")" OBJ, FN_PTR(Unsafe_CompareAndExchangeReference)},
    {CC "compareAndExchangeInt",  CC "(" OBJ "J""I""I"")I", FN_PTR(Unsafe_CompareAndExchangeInt)},
    {CC "compareAndExchangeLong", CC "(" OBJ "J""J""J"")J", FN_PTR(Unsafe_CompareAndExchangeLong)},

    {CC "park",               CC "(ZJ)V",                FN_PTR(Unsafe_Park)},
    {CC "unpark",             CC "(" OBJ ")V",           FN_PTR(Unsafe_Unpark)},

    {CC "getLoadAverage0",    CC "([DI)I",               FN_PTR(Unsafe_GetLoadAverage0)},

    {CC "copyMemory0",        CC "(" OBJ "J" OBJ "JJ)V", FN_PTR(Unsafe_CopyMemory0)},
    {CC "copySwapMemory0",    CC "(" OBJ "J" OBJ "JJJ)V", FN_PTR(Unsafe_CopySwapMemory0)},
    {CC "writeback0",         CC "(" "J" ")V",           FN_PTR(Unsafe_WriteBack0)},
    {CC "writebackPreSync0",  CC "()V",                  FN_PTR(Unsafe_WriteBackPreSync0)},
    {CC "writebackPostSync0", CC "()V",                  FN_PTR(Unsafe_WriteBackPostSync0)},
    {CC "setMemory0",         CC "(" OBJ "JJB)V",        FN_PTR(Unsafe_SetMemory0)},

    {CC "shouldBeInitialized0", CC "(" CLS ")Z",         FN_PTR(Unsafe_ShouldBeInitialized0)},

    {CC "fullFence",          CC "()V",                  FN_PTR(Unsafe_FullFence)},
};

#undef CC
#undef FN_PTR

#undef ADR
#undef LANG
#undef OBJ
#undef CLS
#undef FLD
#undef THR
#undef DC_Args
#undef DAC_Args

#undef DECLARE_GETPUTOOP


/**
 * JVM_RegisterJDKInternalMiscUnsafeMethods - 注册Unsafe类的本地方法
 * 
 * @param env JNI环境指针
 * @param unsafeclass Unsafe类的 jclass 引用
 */
// This function is exported, used by NativeLookup.
// The Unsafe_xxx functions above are called only from the interpreter.
// The optimizer looks at names and signatures to recognize
// individual functions.

JVM_ENTRY(void, JVM_RegisterJDKInternalMiscUnsafeMethods(JNIEnv *env, jclass unsafeclass)) {
  ThreadToNativeFromVM ttnfv(thread);

  int ok = env->RegisterNatives(unsafeclass, jdk_internal_misc_Unsafe_methods, sizeof(jdk_internal_misc_Unsafe_methods)/sizeof(JNINativeMethod));
  guarantee(ok == 0, "register jdk.internal.misc.Unsafe natives");
} JVM_END